package com.jinlejia.erp.ui.mine.assist;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.freedom.yefeng.yfrecyclerview.YfListMode;
import com.freedom.yefeng.yfrecyclerview.YfLoadMoreListener;
import com.jinlejia.erp.R;
import com.jinlejia.erp.adapter.ListMapDropDownAdapter;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.databinding.FragmentInitiatorAssistantBinding;
import com.jinlejia.erp.ui.mine.adapter.InitiatorAdapter;
import com.jinlejia.erp.ui.mine.adapter.TimeDropDownAdapter;
import com.jinlejia.erp.utils.DataFilter;
import com.jinlejia.erp.utils.DateUtil;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;

/**
 * Created by Administrator on 2018/6/1 0001.
 * 发起人Fragment
 */

public class InitiatorFragment extends Fragment implements OnDateSetListener, SwipeRefreshLayout.OnRefreshListener, YfLoadMoreListener {

    private View view;
    private String headers[] = {"协作类型", "生效状态", "发起日期"};
    private String typeData[] = {"不限", "二手房", "租赁", "一手房", "垫资"};
    private String stateData[] = {"不限", "待确认", "已生效", "已完成"};
    private ArrayList<Map<String, Object>> typeList = new ArrayList<>();
    private ArrayList<Map<String, Object>> stateList = new ArrayList<>();
    private List<View> popupViews = new ArrayList<>();
    private String time[] = {"最早日期", "最晚日期"};
    private ListView mTypeView;
    private ListMapDropDownAdapter typeAdapter;
    private ListView mStateView;
    private ListMapDropDownAdapter stateAdapter;
    private ListView mTimeView;
    private TimeDropDownAdapter timeAdapter;

    public String startTime = "";
    public String endTime = "";
    private InitiatorAdapter adapter;

    private ArrayList<Map<String, Object>> dataList = new ArrayList<>();

    private int pageIndex = 1;
    private int type = -1;
    private int state = -1;

    private FragmentInitiatorAssistantBinding binding;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_initiator_assistant, container, false);
        binding = DataBindingUtil.bind(view);
        initView();
        initListener();
        return view;
    }

    private void initView() {
        binding.include.refreshLayout.setColorSchemeResources(R.color.yellow, R.color.light_yellow);
        binding.include.refreshLayout.setOnRefreshListener(this);
        binding.include.dropDownMenu.setTabText(headers[0]);


        for (int i = 0; i < typeData.length; i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("valueName", typeData[i]);
            typeList.add(map);
        }
        mTypeView = new ListView(getActivity());
        typeAdapter = new ListMapDropDownAdapter(getContext(), typeList);
        mTypeView.setAdapter(typeAdapter);
        for (int i = 0; i < stateData.length; i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("valueName", stateData[i]);
            stateList.add(map);
        }
        mStateView = new ListView(getActivity());
        stateAdapter = new ListMapDropDownAdapter(getContext(), stateList);
        mStateView.setAdapter(stateAdapter);

        final View priceAreaFooter = getActivity().getLayoutInflater().inflate(R.layout.time_menu_footer, null);
        mTimeView = new ListView(getActivity());
        timeAdapter = new TimeDropDownAdapter(getContext(), Arrays.asList(time));
        mTimeView.addFooterView(priceAreaFooter);
        mTimeView.setAdapter(timeAdapter);
        //重置、确定按钮
        TextView cancel = priceAreaFooter.findViewById(R.id.bt_cancel);
        TextView confirm = priceAreaFooter.findViewById(R.id.bt_confirm);
        //点击重置
        cancel.setOnClickListener(v -> {
            timeAdapter.startTime = "";
            timeAdapter.endTime = "";
            startTime = "";
            endTime = "";
            binding.include.dropDownMenu.setTabText("发起日期");
            timeAdapter.notifyDataSetChanged();
        });

        //确定按钮
        confirm.setOnClickListener(v -> {
            if (!TextUtils.isEmpty(startTime) || !TextUtils.isEmpty(endTime)) {
                jsonObject.put("initiateTimeMin", startTime);
                jsonObject.put("initiateTimeMax", endTime);
            } else {
                jsonObject.remove("initiateTimeMin");
                jsonObject.remove("initiateTimeMax");
            }
            getData();
            binding.include.dropDownMenu.closeMenu();
        });

        popupViews.add(mTypeView);
        popupViews.add(mStateView);
        popupViews.add(mTimeView);

        TextView contentView = new TextView(getActivity());
        contentView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0));
        contentView.setGravity(Gravity.CENTER);

        binding.include.dropDownMenu.setDropDownMenu(Arrays.asList(headers), popupViews, contentView);

        binding.include.contractRecyclerView.setHasFixedSize(true);
        binding.include.contractRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        binding.include.contractRecyclerView.enableAutoLoadMore(this);
        adapter = new InitiatorAdapter(dataList);
        adapter.changeMode(YfListMode.MODE_LOADING);
        binding.include.contractRecyclerView.setAdapter(adapter);
        binding.include.refreshLayout.setRefreshing(false);

    }

    @Override
    public void onStart() {
        super.onStart();
        getData();
    }

    private void initListener() {
        mTypeView.setOnItemClickListener((adapterView, view, position, l) -> {
            typeAdapter.setCheckItem(position);
            binding.include.dropDownMenu.setTabText(position == 0 ? headers[0] : typeList.get(position).get("valueName").toString());
            binding.include.dropDownMenu.closeMenu();
            pageIndex = 1;
            type = position - 1;
            getData();
        });

        mStateView.setOnItemClickListener((adapterView, view, position, l) -> {
            stateAdapter.setCheckItem(position);
            binding.include.dropDownMenu.setTabText(position == 0 ? headers[1] : stateList.get(position).get("valueName").toString());
            binding.include.dropDownMenu.closeMenu();
            state = position - 1;
            getData();
        });

        adapter.setOnItemClickListener((view, o) -> {
            Intent intent = new Intent(getActivity(), AssistInfoActivity.class);
            intent.putExtra("id", ((Map<String, Object>) o).get("id").toString());
            startActivity(intent);
        });

        mTimeView.setOnItemClickListener((adapterView, view, i, l) -> {
            timeAdapter.setCheckItem(i);
            show(time[i]);
        });

    }

    /**
     * @param title
     */
    private void show(String title) {
        TimePickerDialog timePicker = new TimePickerDialog.Builder()
                .setType(Type.YEAR_MONTH_DAY)
                .setTitleStringId(title)
                .setCurrentMillseconds(System.currentTimeMillis())
                .setThemeColor(getResources().getColor(R.color.yellow))
                .setWheelItemTextNormalColor(getResources().getColor(R.color.hintColor))
                .setWheelItemTextSelectorColor(getResources().getColor(R.color.yellow))
                .setCallBack(this)
                .build();
        timePicker.show(getActivity().getSupportFragmentManager(), "year_month_day");
    }

    private JSONObject jsonObject = new JSONObject();

    private boolean mLoadingLock = false;

    /**
     * 获取数据
     */
    private void getData() {
        mLoadingLock = true;
        if (type != -1) {
            jsonObject.put("type", type);
        } else {
            jsonObject.remove("type");
        }
        if (state != -1) {
            jsonObject.put("state", state);
        } else {
            jsonObject.remove("state");
        }
        jsonObject.put("pageSize", 10);
        jsonObject.put("pageIndex", pageIndex);
        OkHttpUtils
                .postString()
                .url(ApiConfig.ASSIST_INITIATOR_LIST)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(jsonObject.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        ArrayList<Map<String, Object>> arrayList = null;
                        if (binding.include.refreshLayout.isRefreshing()) {
                            binding.include.refreshLayout.setRefreshing(false);
                        }
                        if (DataFilter.filter(getActivity(), response, adapter)) {
                            JSONObject jsonObject = JSON.parseObject(response.toString());
                            arrayList = JSON.parseObject(jsonObject.getJSONArray("data").toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                            });
                            if (pageIndex == 1) {
                                adapter.setData(arrayList);
                            } else {
                                adapter.addData(arrayList);
                            }
                        } else if (response.get("code").toString().equals("303")) {
                            //没有更多
                            pageIndex--;
                        } else if (response.get("code").toString().equals("501")) {
                            adapter.changeMode(YfListMode.MODE_EMPTY);
                        }
                        if (adapter.getFooters().size() > 0)
                            adapter.removeAllFooters();
                        mLoadingLock = false;
                    }
                });
    }

    @Override
    public void onRefresh() {
        pageIndex = 1;
        getData();
    }

    @Override
    public void loadMore() {
        if (mLoadingLock) {
            return;
        }
        pageIndex++;
        adapter.addFooter("加载中");
        getData();
    }

    @Override
    public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
        if (timePickerView.getTitle().equals("最早日期")) {
            startTime = DateUtil.getTimeStart(millseconds);
            timeAdapter.startTime = startTime;
        } else if (timePickerView.getTitle().equals("最晚日期")) {
            endTime = DateUtil.getTimeEnd(millseconds);
            timeAdapter.endTime = endTime;
        }
        timeAdapter.notifyDataSetChanged();
        if (!TextUtils.isEmpty(startTime) && !TextUtils.isEmpty(endTime)) {
            binding.include.dropDownMenu.setTabText(startTime + "—" + endTime);
        } else {
            binding.include.dropDownMenu.setTabText(startTime + endTime);
        }
    }

}
